import 'dart:async';
// import 'dart:math';
import 'package:bitcoin_mine/common/global.dart';
// import 'package:decimal/decimal.dart';
// import 'package:flustars/flustars.dart';
import 'package:get/get.dart';

class BalanceAnimationController extends GetxController {
  // 当前显示的余额
  // RxDouble displayBalance = 0.0.obs;
  // 当前显示的余额(整数单位)，用于无损显示
  Rx<BigInt> displayBalanceUnits = BigInt.zero.obs;

  // 高精度整数余额（单位：1e-15 BTC），用于避免双精度丢失
  BigInt _balanceUnits = BigInt.zero;
  static const int _scale = 15; // 1e-15 单位
  static const double _scalePow = 1e15; // for fast double 除法

  // 定时器
  Timer? _timer;

  // 动画是否运行
  final RxBool isAnimating = false.obs;

  @override
  void onInit() {
    super.onInit();
    startAnimation();
    Global.totalHashrate.listen((event) {
      print("totalHashrate = $event");
      stopAnimation();
      startAnimation();
    });
    Global.mineInfo.listen((event) {
      print("mineInfo = ${event?.user_info?.balance}");
      stopAnimation();
      startAnimation();
    });
  }

  @override
  void onClose() {
    stopAnimation();
    super.onClose();
  }

  /// 开始数值增长动画
  void startAnimation() {
    if (_timer != null) return;
    final double initBalance = Global.mineInfo.value?.user_info?.balance ?? 0.0;
    print("initBalance = $initBalance");
    // 初始化整数余额单位
    _balanceUnits = _toUnits(initBalance);
    displayBalanceUnits.value = _balanceUnits;
    print('init _balanceUnits: $_balanceUnits');
    // displayBalance.value = _unitsToDouble(_balanceUnits);
    // print('init displayBalance: ${displayBalance.value}');
    try {
      isAnimating.value = true;

      // 每秒更新一次数值
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        try {
          // 单位增量：hashrate * 1e-14 BTC/s -> 在 1e-16 单位下 = hashrate * 100
          final double totalHashrate = Global.totalHashrate.value.toDouble();
          final BigInt incrementUnits = BigInt.from(
            (totalHashrate * 100).round(),
          );
          _balanceUnits = _balanceUnits + incrementUnits;
          displayBalanceUnits.value = _balanceUnits;
          // print('incrementUnits: $incrementUnits');
          // print('balanceUnits: ${_balanceUnits}');
          // displayBalance.value = _unitsToDouble(_balanceUnits);
          // print('displayBalance: ${displayBalance.value}');
        } catch (e) {
          print('动画更新错误: $e');
        }
      });
    } catch (e) {
      print('启动动画错误: $e');
      isAnimating.value = false;
    }
  }

  /// 停止数值增长动画
  void stopAnimation() {
    try {
      _timer?.cancel();
      _timer = null;
      isAnimating.value = false;
    } catch (e) {
      print('停止动画错误: $e');
    }
  }

  /// 暂停动画
  void pauseAnimation() {
    _timer?.cancel();
    _timer = null;
    isAnimating.value = false;
  }

  /// 恢复动画
  void resumeAnimation() {
    if (_timer != null) return;
    startAnimation();
  }

  // 已弃用：使用高精度整数路径

  // 将 double 转换为 1e-16 单位的 BigInt，避免 double->int 溢出
  BigInt _toUnits(double value) {
    final String s = value.toStringAsFixed(_scale);
    final bool neg = s.startsWith('-');
    final String digits = s.replaceAll('-', '').replaceAll('.', '');
    BigInt units = BigInt.parse(digits);
    return neg ? -units : units;
  }

  // 将单位整数转换为 double 展示
  double _unitsToDouble(BigInt units) {
    // 使用浮点除法即可，展示层允许双精度
    return units.toDouble() / _scalePow;
  }
}
